package vn.edu.uit.game_show;

import java.io.IOException;
import java.net.UnknownHostException;

import vn.edu.uit.game_show.QRCode.IntentIntegrator;
import vn.edu.uit.game_show.QRCode.IntentResult;
import vn.edu.uit.game_show.utilities.TCPClient;
import vn.edu.uit.game_show.utilities.TCPServerCommand;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ThietLap extends Activity {

	Button btnDiemDanh;
	Button btnTTGV;
	
	TCPServerCommand serverCommand;

	ImageView imgQRCode;
	String path = Environment.getExternalStorageDirectory().getAbsolutePath()
			.toString()
			+ "/game/qrcode.png";

	public String ip = "";
	public String port = "";
	public String hoten = "";
	public String msgv = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_thiet_lap);
		
		serverCommand = new TCPServerCommand(this);
		serverCommand.start();

		btnDiemDanh = (Button) findViewById(R.id.btnQuetQRCode);
		btnDiemDanh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				IntentIntegrator integrator = new IntentIntegrator(
						ThietLap.this);
				integrator.initiateScan();
			}
		});

		btnTTGV = (Button) findViewById(R.id.btnTTGV);
		btnTTGV.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
				hoten = prefs.getString("hoten", "").toString();
				msgv = prefs.getString("msgv", "").toString();
				ip = prefs.getString("ip", "").toString();
				port = prefs.getString("port", "").toString();

				if (ip.equals("")) {
					Toast.makeText(getApplicationContext(),
							"Chưa kết nối với giáo viên!", Toast.LENGTH_SHORT)
							.show();
				} else {
					final Dialog dialog = new Dialog(ThietLap.this);
					dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
					dialog.setContentView(R.layout.dialog_thong_tin_socket);
					dialog.setCancelable(true);

					TextView tvTitle = (TextView) dialog
							.findViewById(R.id.tvTitle);
					tvTitle.setText("Thông tin giáo viên");

					TextView tvHoten = (TextView) dialog
							.findViewById(R.id.tvHoten);
					tvHoten.setText(hoten);
					TextView tvMSHS = (TextView) dialog
							.findViewById(R.id.tvMSHS);
					tvMSHS.setText(msgv);

					TextView tvIP = (TextView) dialog.findViewById(R.id.tvIP);
					tvIP.setText(ip);
					TextView tvPort = (TextView) dialog
							.findViewById(R.id.tvPort);
					tvPort.setText(port);

					Button btnOK = (Button) dialog.findViewById(R.id.btnOK);
					btnOK.setOnClickListener(new OnClickListener() {

						public void onClick(View v) {
							dialog.dismiss();
						}
					});

					dialog.show();
				}
			}
		});

		imgQRCode = (ImageView) findViewById(R.id.imgQRCode);
		imgQRCode.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				SharedPreferences prefs = getSharedPreferences("TaiKhoanNhom", 0);
				hoten = prefs.getString("tenNhom", "").toString();
				ip = prefs.getString("ip", "").toString();
				port = prefs.getString("port", "").toString();

				final Dialog dialog = new Dialog(ThietLap.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.dialog_thong_tin_socket);
				dialog.setCancelable(true);

				TextView tvTitle = (TextView) dialog.findViewById(R.id.tvTitle);
				tvTitle.setText("Thông tin nhóm");

				TextView tvHoten = (TextView) dialog.findViewById(R.id.tvHoten);
				tvHoten.setText(hoten);
				
				TextView tvTitleMS = (TextView) dialog.findViewById(R.id.tvTitleMSHS);
				tvTitleMS.setVisibility(View.GONE);
				TextView tvMS = (TextView) dialog.findViewById(R.id.tvMSHS);
				tvMS.setVisibility(View.GONE);
				
				TextView tvIP = (TextView) dialog.findViewById(R.id.tvIP);
				tvIP.setText(ip);
				TextView tvPort = (TextView) dialog.findViewById(R.id.tvPort);
				tvPort.setText(port);

				Button btnOK = (Button) dialog.findViewById(R.id.btnOK);
				btnOK.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						dialog.dismiss();
					}
				});

				dialog.show();
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		imgQRCode.setImageBitmap(BitmapFactory.decodeFile(path));
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		IntentResult scanResult = IntentIntegrator.parseActivityResult(
				requestCode, resultCode, intent);

		if (scanResult.getRawBytes() != null) {
			String barcode;
			String[] values;
			barcode = scanResult.getContents();
			values = barcode.split("#");

			if (Integer.parseInt(values[0].toString()) == 0) {
				SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
				SharedPreferences.Editor editor = prefs.edit();
				editor.putString("hoten", values[1].toString());
				editor.putString("msgv", values[2].toString());
				editor.putString("ip", values[3].toString());
				editor.putString("port", values[4].toString());
				editor.commit();

				Toast.makeText(getApplicationContext(),
						"Đã kết nối máy giáo viên", Toast.LENGTH_LONG).show();
				
				new SendInfoAsyncTask(values[3].toString(), Integer.parseInt(values[4].toString())).execute();
				
			}

		}
	}
	
	final class SendInfoAsyncTask extends AsyncTask<Void, Void, Void> {

		Context ctx;
		
		String host = "";
		int port = 54321;
		
		public SendInfoAsyncTask(String _host, int _port) {
			ctx = ThietLap.this;
			this.host = _host;
			this.port = _port;
		}
		
		@Override
		protected Void doInBackground(Void... arg0) {
			try {
				TCPClient client = new TCPClient(ctx, host, port);
				client.guiThongTin();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.getInstance().clearApplicationData();
			int pid = android.os.Process.myPid();
			android.os.Process.killProcess(pid);
			System.exit(0);
			return false;
		}
		return false;
	}
}
